package com.spring.nio.service.file.handler;

import com.spring.nio.core.channel.context.ChannelContext;
import com.spring.nio.core.channel.handler.AbstractChannelHandler;
import com.spring.nio.core.event.listener.event.constant.ExceptionEventTypeEnum;
import com.spring.nio.core.event.listener.event.model.ExceptionEventSource;
import com.spring.nio.core.event.listener.event.model.NioReadExceptionEventSource;
import com.spring.nio.core.event.model.PacketData;
import com.spring.nio.core.exception.ExceptionManager;
import com.spring.nio.service.file.frame.FileMessageFrame;
import com.spring.nio.service.file.util.FileTransportManager;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;

/**
 * 文件读事件真实数据处理器 --> 负责封装传送文件信息
 * @author spring
 * */
@Slf4j
public class FileRealDataHandler extends AbstractChannelHandler {

    /**
     * @param o              
     * @param channelContext
     * @throws IOException
     */
    @Override
    public void handler(Object o, ChannelContext channelContext) {
        final PacketData packetData = (PacketData) o;
        // 处理文件数据(realList 中可能包含多个待处理文件)
        packetData.getSocketChannelContext().getRealList().forEach(obj -> {
            try {
                FileTransportManager.executeFileTransportHandler((FileMessageFrame) obj, packetData.getSocketChannelContext(), channelContext);
            } catch (IOException e) {
                // 异常事件(ExceptionEvent) 事件源类型为异常事件源类型(EXCEPTION_EVENT_SOURCE)  事件源数据(NioReadEventExceptionSource)
                ExceptionEventSource exceptionEventSource = new ExceptionEventSource();
                exceptionEventSource.setSocketChannelContext(packetData.getSocketChannelContext());
                exceptionEventSource.setModule("FileRealDataHandler --> method [handler] --> 产生异常");
                exceptionEventSource.setException(e);
                exceptionEventSource.setExceptionEventTypeEnum(ExceptionEventTypeEnum.FILE_TRANSPORT_HANDLER_IO_EXCEPTION);
                exceptionEventSource.setIsSend(Boolean.TRUE);
                ExceptionManager.handleException(exceptionEventSource);
            }
        });
    }
}
